package com.qf.service.impl;

import com.qf.dao.CartDao;
import com.qf.dao.OrderItemDao;
import com.qf.dao.impl.CartDaoImpl;
import com.qf.dao.impl.OrderDaoImpl;
import com.qf.dao.OrderDao;
import com.qf.dao.impl.OrderItemDaoImpl;
import com.qf.pojo.Goods;
import com.qf.pojo.Order;
import com.qf.pojo.OrderItem;
import com.qf.pojo.ShopItem;
import com.qf.service.OrderService;
import com.qf.utils.DBTools;
import com.qf.utils.UpdateException;

import java.util.Collection;

public class OrderServicImpl implements OrderService {

    private CartDao cartDao=new CartDaoImpl();
    private OrderDao orderDao=new OrderDaoImpl();
    private OrderItemDao orderItemDao=new OrderItemDaoImpl();

    @Override
    public int addOrder(Order order, Collection<ShopItem> shopItems) {
        try{
            //开启事务
            DBTools.startTransaction();

            //1.order订单的生成
            int res=orderDao.insert(order);
            if (res == 0) {
                throw new UpdateException("订单储存失败！");
            }

            for (ShopItem item:shopItems){

                Goods goods=item.getGoods();
                //2.CART表中删除数据
                if(cartDao.selectOne(order.getUid(),goods.getId())!=null){
                    res=cartDao.deleteOne(order.getUid(),goods.getId());
                    if (res == 0) {
                        throw new UpdateException("删除购物车信息失败！");
                    }
                }

                //3.order—item订单明细的生成
                //public OrderItem(Integer gid, String oid, String pic, Float price, Integer gnum, String gname) {}
                OrderItem orderItem=new OrderItem(goods.getId(),order.getOid(),goods.getPic1(),
                                                  goods.getPrice(), item.getNum(),goods.getName());
                res=orderItemDao.insert(orderItem);
                if (res == 0) {
                    throw new UpdateException("订单明细储存失败！");
                }
            }
            //事务提交
            DBTools.commit();
            return 1;
        }
        catch (Exception e){
            //出异常，回滚事务
            DBTools.rollback();
            e.printStackTrace();
        }
        return 0;
    }
}
